#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<dirent.h>
#include<stdlib.h>
#include<string.h>

#define DESTDIR "/home/sh/workshop/os-exp/destdir"

int myls(char* dirpath){
    struct dirent *ep;
    char* filepath = (char*)malloc(120);
    DIR* dp = opendir(dirpath);
    if(dp==NULL){
        printf("directory not exists.\n");
        return 0;
    }else{
        while(ep = readdir(dp)){
            struct stat st;
            sprintf(filepath,"%s/%s",dirpath,ep->d_name);
            if(stat(filepath,&st)==-1){
                printf("read failed.\n");
                return 0;
            }
            if(strcmp(ep->d_name,".")==0||strcmp(ep->d_name,"..")==0){
                //DO NOTHING
            }else if(S_ISDIR(st.st_mode)){//调用子进程遍历目录
                int pid=fork();
                if(pid<0){
                    printf("fork failed.\n");
                    exit(0);
                }else if(pid>0){//父进程等待子进程运行完成
                    waitpid(pid,NULL,0);
                }else{//子进程调用main遍历
                    execl("/home/sh/workshop/os-exp/exp4/main.out","main.out",filepath,(char*)0);
                    exit(0);
                }
                // myls(filepath);//递归处理，其他的方法暂时不知道怎么做
            }else{//开始调用子进程复制文件
                int pid=fork();
                if(pid<0){
                    printf("fork failed.\n");
                    exit(0);
                }else if(pid>0){//父进程等待子进程运行完成
                    waitpid(pid,NULL,0);
                }else{//子进程开始干活
                    execl("/home/sh/workshop/os-exp/exp2/mycp.out","mycp.out",filepath,DESTDIR,(char*)0);
                    exit(0);
                }
            }
        }
    }
    closedir(dp);
}

int main(int argc, char* argv[]){
    //TODO
    struct dirent *ep;
    char* dirpath = (char*)malloc(255);
    char* filepath = (char*)malloc(255);
    char** file_stack = (char**)malloc(100*sizeof(char*));
    int count = 0;
    if(argc>2){
        printf("%s requires 1 arguments, but got %d.\n",argv[0],argc-1);
        exit(0);
    }else if(argc == 1){
        getcwd(dirpath,255);
    }else if(argc == 2){
        strcpy(dirpath,argv[1]);
    }
    myls(dirpath);
    return 0;
}